<template>
    <li>
      <div
        :class="{bold: isFolder}"
        @click="toggle"
        @dblclick="changeType">
        {{ model.name }}
        <span v-if="isFolder">[{{ open ? '-' : '+' }}]</span>
      </div>
      <ul v-show="open" v-if="isFolder" class="tree-item">
        <item
          class="item"
          v-for="(model, index) in model.children"
          :key="index"
          :model="model">
        </item>
        <li class="add" @click="addChild">+</li>
      </ul>
    </li>
</template>

<script>
  export default {
    name: "item",
    data(){
      return {
        open: false
      }
    },
    props: {
      model: Object
    },
    computed: {
      isFolder: function () {
        return this.model.children &&
          this.model.children.length
      }
    },
    methods: {
      toggle: function () {
        if (this.isFolder) {
          this.open = !this.open
        }
      },
      changeType: function () {
        if (!this.isFolder) {
          Vue.set(this.model, 'children', [])
          this.addChild()
          this.open = true
        }
      },
      addChild: function () {
        this.model.children.push({
          name: 'new stuff'
        })
      }
    }
  }
</script>

<style scoped>
  .item {
    cursor: pointer;
  }
  .bold {
    font-weight: bold;
    line-height: 1.5;
  }
  .tree-item {
    padding-left: 20px;
    line-height: 1.5;
  }
</style>
